<?php

namespace addons\Holiday\api\modules\v1\controllers;

use Yii;
use yii\data\ActiveDataProvider;
use yii\web\NotFoundHttpException;
use common\helpers\ArrayHelper;
use api\controllers\OnAuthController;
use addons\Flow\common\models\Works;
use addons\Holiday\common\models\Holiday;
use addons\Holiday\common\models\HolidayCate;

/**
 * @property \yii\db\ActiveRecord|\yii\base\Model $modelClass;
 * @author 古月 <21931118@qq.com>
 */
class DefaultController extends OnAuthController
{
    public $modelClass = Holiday::class;

    /**
     * 不用进行登录验证的方法
     * 例如： ['index', 'update', 'create', 'view', 'delete']
     * 默认全部需要验证
     *
     * @var array
     */
    protected $authOptional = ['index', 'view','type'];

    public function actionIndex()
    {
        return new ActiveDataProvider([
            'query' => $this->modelClass::find()
                ->andWhere(['member_id' => Yii::$app->user->identity->member_id])
                ->andFilterWhere(['cate_id' => Yii::$app->request->get('cate_id')])
                ->orderBy('id desc')
                ->with('member','cate')
                ->asArray(),
            'pagination' => [
                'pageSize' => $this->pageSize,
                'validatePage' => false,// 超出分页不返回data
            ],
        ]);
    }
    public function actionView($id)
    {
        $model = $this->modelClass::findOne($id);
        $radioList = [];
        foreach ($model->getNextStatuses() as $key => $nextStatus) {
            $radioList[$key] = $nextStatus['status']->getLabel();
        }
        foreach ($model->log as $key=>$log){
            $log->name = Yii::$app->flowService->member->getName($log->id);
            if($key==0) $log->suggest = '提交申请';
            $log->approve = \addons\Flow\common\enums\WorkflowEnum::getValue(explode('/', $log->action)[1]);
        }

        $model->log = array_reverse($model->log);
        return ['cate'=>$model->cate,'model'=>$model,'radioList'=>ArrayHelper::arrayToArrays($radioList)];
    }
    public function actionType()
    {
        $model = HolidayCate::find()->select(['id','title'])->where(['merchant_id'=>Yii::$app->user->identity->merchant_id])->orderBy('sort asc')
            ->asArray()->all();
        return $model;
    }
    public function actionDelete($id)
    {
        if ($this->findModel($id)->state == 'apply') {
            // 事务
            $transaction = Yii::$app->db->beginTransaction();
            try {
                Works::deleteAll(["workflow_id" => 'Holiday', 'work_id' => $id]);
                $this->modelClass::deleteAll(["state" => 'apply', 'id' => $id]);
                $transaction->commit();
                return ('删除成功');
            } catch (\Exception $e) {
                $transaction->rollBack();
                return (Yii::$app->request->referrer);
            }
        } else return ('正在审核中，不能删除');

    }
    protected function findModel($id)
    {
        /* @var $model \yii\db\ActiveRecord */
        if (empty($id) || !($model = $this->modelClass::findOne($id))) {
            throw new NotFoundHttpException('请求的数据不存在');
        }
        return $model;
    }

    /**
     * 权限验证
     *
     * @param string $action 当前的方法
     * @param null $model 当前的模型类
     * @param array $params $_GET变量
     * @throws \yii\web\BadRequestHttpException
     */
    public function checkAccess($action, $model = null, $params = [])
    {
        if (in_array($action, [])) {
            throw new \yii\web\BadRequestHttpException('权限不足');
        }
    }
}
